import 'package:casdon/modules/recipe/data/api/recipe_module_content_api.dart';
import 'package:casdon/modules/recipe/data/model/recipe_module_content_model.dart';
import 'package:casdon/modules/recipe/domain/states/recipe_module_content_state.dart';
import 'package:casdon/modules/recipe/providers/recipe_provider.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

// 菜谱模块的内容，可能是活动，菜谱集，烹饪课程等
class RecipeModuleContentNotifier
    extends FamilyAsyncNotifier<RecipeModuleContentState, String> {
  late final String moduleId;
  int pageSize = 10;
  int pageNum = 1;
  int totalSize = 0;
  bool _isLoadingMore = false;
  bool _isRefreshing = false;

  @override
  Future<RecipeModuleContentState> build(String arg) async {
    moduleId = arg;
    pageNum = 1;
    final previous = state.valueOrNull;
    try {
      return await _fetchData();
    } catch (_) {
      return previous ?? RecipeModuleContentState.initial();
    }
  }

  Future<void> refresh() async {
    if (_isRefreshing) return;
    _isRefreshing = true;
    final previous = state.valueOrNull;
    try {
      pageNum = 1;
      final newState = await _fetchData();
      state = AsyncValue.data(newState);
    } catch (e, st) {
      if (previous != null) {
        state = AsyncValue.data(previous);
      } else {
        state = AsyncValue.data(RecipeModuleContentState.initial());
      }
    } finally {
      _isRefreshing = false;
    }
  }

  bool get hasMore {
    final currentState = state.valueOrNull;
    if (currentState == null) return true;
    if (totalSize == 0) return true;
    return currentState.data.length < totalSize;
  }

  Future<void> loadMore() async {
    if (_isLoadingMore || !hasMore) return;
    final currentState = state.valueOrNull;
    if (currentState == null) return;

    _isLoadingMore = true;
    final previousPage = pageNum;
    try {
      pageNum += 1;
      final nextState = await _fetchData();
      final merged = [...currentState.data, ...nextState.data];

      state = AsyncValue.data(currentState.copyWith(data: merged));
    } catch (_) {
      pageNum = previousPage;
      state = AsyncValue.data(currentState);
    } finally {
      _isLoadingMore = false;
    }
  }

  Future<RecipeModuleContentState> _fetchData() async {
    PageQuery page = PageQuery(pageNum: pageNum, pageSize: pageSize);
    RequestRecipeModuleContentApi request = RequestRecipeModuleContentApi(
      moduleId: moduleId,
      pageQuery: page,
    );
    final ret = await ref
        .read(recipeModuleContentUsecaseProvider)
        .execute(request);
    totalSize = ret.total;
    return RecipeModuleContentState(
      data: RecipeModuleContentModel.listFromApi(ret.rows),
    );
  }
}
